package com.cnhis.cloudhealth.clidoctorweb.gzip;

import java.io.ByteArrayOutputStream;
import java.io.File;
//package me.gacl.web.filter;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.zookeeper.common.PathUtils;

/**
 * 使用注解标注过滤器
 * 
 * @WebFilter将一个实现了javax.servlet.Filte接口的类定义为过滤器 属性filterName声明过滤器的名称,可选
 *                                               属性urlPatterns指定要过滤
 *                                               的URL模式,也可使用属性value来声明.(
 *                                               指定要过滤的URL模式是必选属性)
 */
@WebFilter(filterName = "zipFilter1", urlPatterns = "/dddd*")
public class zipFilter1 implements Filter {

	@Override
	public void destroy() {
		System.out.println("过滤器销毁");
	}

	@SuppressWarnings("unchecked")
	@Override
	public void doFilter(ServletRequest request, ServletResponse response1, FilterChain chain)
			throws IOException, ServletException {

		// System.out.println("---request.getServletContext():" +
		// request.getServletContext().);
		System.out.println("---执行过滤操作");

		HttpServletResponse response = (HttpServletResponse) response1;
		String requestURL = ((HttpServletRequest) request).getRequestURL().toString();
		System.out.println("---request.request).getRequestURL():" + requestURL);
		if (requestURL.contains("laypage.js"))
			System.out.println("dbg");

		// 创建HttpServletResponse 包装类的实例
		MyHttpServletResponse myResponse = new MyHttpServletResponse((HttpServletResponse) response);

		chain.doFilter(request, myResponse);

		// myResponse.get

		// GZIP压缩：
		byte[] buff = myResponse.getBufferedBytes();
	//	if (requestURL.contains("laypage.js"))
	//		System.out.println(" buff len:" + buff.length);

		
//if jpg gif png not zip
		if (requestURL.toLowerCase().endsWith(".jpg") || requestURL.toLowerCase().endsWith(".png")
				|| requestURL.toLowerCase().endsWith(".gif")) {
			  outputOri(response, buff);
			return;
		}
		
		
		// if not compressableMimeType ,out ori if not txt ,no zip
		String compressableMimeType = "text/html,text/xml,text/javascript,text/css,text/plain,application/json,application/javascript"; 
		String ContentType = response.getContentType();
		
		try {
			if(ContentType!=null&& ContentType.toLowerCase().contains("application/json"))
			{
				saveLoginfo("c:\\0log",PathUtil.toFilenameEncode(requestURL)+".txt",buff);
			}
		} catch (Exception e) {
		e.printStackTrace();
		}
		
		// String ContentType2 = myResponse.getHeader("Content-Type");
		if (ContentType != null && !Strutil.containsAny_sf(ContentType, Strutil.toSet(compressableMimeType, ","))) {
			outputOri(response, buff);
			return;
		}
		if(ContentType==null)  //ori
		{
			outputOri(response, buff);
			return;
		}
		
		
	//if is txt and leng <5
		if (buff.length < 5 * 1000) {
			  outputOri(response, buff);
			return;
		}

		
		//------------is txt and len>5 ,will be zip
		// 创建缓存容器：
		byte[] buff_ziped=GzipUtil.gzip(buff);
		 

		// 设置响应头；
		response.setHeader("Content-Encoding", "gzip");
		outputOri(response, buff_ziped);

	}

	private void saveLoginfo(String dir, String f, byte[] buff) {
		 try {
			FileUtils.writeByteArrayToFile(new File(dir+"\\"+f),buff );
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

	private boolean isAjaxData(String requestURL, String string) {
		// TODO Auto-generated method stub
		return false;
	}

	private void outputOri(HttpServletResponse response, byte[] buff) throws IOException {
		response.setContentLength(buff.length);
		  response.getOutputStream().write(buff);
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		System.out.println("--过滤器初始化");
	}
}